/*
 * 组织界面js
 * 依赖组件[bootstrapTable]
 */
(function() {
	/*'use strict';*/
	
	require(['navigation', 'jquery', 'box', 'bootstrapTable', 'bootstrapTableZh', 'form', 'select2'], 
			function(navigation, jquery, box) {
		if(typeof jQuery === 'undefined') {	//检测jquery依赖项
			throw new Error('jquery依赖项未能加载');
		}
		
		if(typeof $.fn.bootstrapTable === 'undefined') {	//检测bootstrapTable依赖项
			throw new Error('bootstrapTable依赖项未能加载');
		}
		
		if(typeof $.fn.form === 'undefined') {
			throw new Error('form依赖项未能加载');
		}
		
		var tipModal = box.tipModal,
			readOnlyModal = box.readOnlyModal;
		
		var tableFn = function(obj) {
			if(Object.prototype.toString() != '[object Object]') {
				return false;
			}
			
			var $table = $('#' + obj.tableId),	//jquery包装table对象，使其能够调用扩展后jquery的方法
				$addBtn = $('#' + obj.addBtnId),
				formId = obj.formId,
				formId2 = obj.formId2;
		    	selections = [],
		    	columns = obj.columns, cLength = columns.length;
		
			function initTable() {	//加载内容
				columns[cLength] = {
		  				width: '18%',
		  				field: 'crud',
		  				title: '操作',
		  				valign: 'top',
		  				align: 'center',
		  				events: operateEvents,
		                formatter: operateFormatter
					};
				
		        $table.bootstrapTable({
					locale: 'zh-CN',
					width: '90%',
		            columns: columns,
					  formatLoadingMessage: function () {
					    return "请稍等，正在加载中...";
					  },
					  formatNoMatches: function () {  //没有匹配的结果
						return '无符合条件的记录';
					  },
					  onLoadError: function (data) {
						  $table.bootstrapTable('removeAll');
					  },
		        });
		        setTimeout(function () {
		            $table.bootstrapTable('resetView');
		        }, 200);
		        
		        $table.on('expand-row.bs.table', function (e, index, row, $detail) {
		        	var detail = detailFormatter(index, row);
		        	$detail.html(detail);
		        });
		        $table.on('all.bs.table', function (e, name, args) {
		            console.log(name, args);
		        });
		    }
			
		    function getIdSelections() {
		        return $.map($table.bootstrapTable('getSelections'), function (row) {
		            return row.id;
		        });
		    }
		    
		    function responseHandler(res) {
		        $.each(res.rows, function (i, row) {
		            row.state = $.inArray(row.id, selections) !== -1;
		        });
		        return res;
		    }
		    
		    /*table中  “+” 按钮添加内容*/
		    function detailFormatter(index, row) {
		        var html = [], Updater = "", updateTime = "";
		        if(row.updatetime == null || row.updater == null){
		        	Updater = "无";
		        	updateTime = "无";
		        }else {
			    	Updater = row.updater;
			    	updateTime = new Date(row.updatetime).toLocaleString();
		        }
	            html.push('<p><b>创建者 :</b> ' + row.creater + '</p>'+
	            		'<p><b>创建时间 :</b> ' + new Date(row.createtime).toLocaleString() + '</p>'+
	            		'<p><b>更新者 :</b> ' + Updater + '</p>'+
	            		'<p><b>更新时间:</b> ' + updateTime + '</p>');
		        return html.join('');
		    }
		    
		    function operateFormatter(value, row, index) {
		        return [
					'<a class="remove" href="javascript:void(0)" title="Remove">',
					'<i class="glyphicon glyphicon-remove"></i>',
					'</a>  ',
					'<a class="edit" href="javascript:void(0)" title="edit">',
					'<i class="glyphicon glyphicon-edit"></i>',
					'</a>  ',
		            '<a class="resetpass" href="javascript:void(0)" title="resetpass">',
		            '<i class="glyphicon glyphicon-repeat"></i>',
		            /*'<i class="icon iconfont1">&#xe60d;</i>',*/
		            '</a>  ',
		            '<a class="group" href="javascript:void(0)" title="group">',
		            '<i class="glyphicon glyphicon-user"></i>',
		           /* '<i class="icon iconfont1">&#xe72b;</i>',*/
		            '</a>  '
		        ].join('');
		    }
		    window.operateEvents = {
		        'click .remove': function (e, value, row, index) {
		        	var name = row.name;
		        	var modalObj = box.configModal('subContent'),
		        		modalId = modalObj.modalId, modalBodyId = modalObj.modalBodyId, btnSure = modalObj.btnSure;
		        	var modal = $('#' + modalId), 
	    				btn_sure = $('#' + btnSure);
		        	$('#' + modalBodyId).html('确定要删除"' + name + '"吗？');
		        	modal.modal({backdrop: "static"});
		        	
		        	btn_sure.unbind("click").bind("click", function() {
		        		btn_sure.attr('disable', true);
		        		$.ajax({
			        		url: "user/deleteUser.service",
			        		type: "post",
			        		data: {id: row.id},
			        		success: function(data) {
			        			if(data && data.success) {
			        				getUsers($('#person_add').data('oid'));
			        				modal.modal("hide");
			        			}else{
					        		var modalObj = box.tipModal('subContent'),
		    			        		modalId = modalObj.modalId, modalBodyId = modalObj.modalBodyId;
		    			        	var tip_modal = $('#' + modalId);
					        		modal.modal("hide");
					        		$('#' + modalBodyId).html('成员删除失败。。。。');
					        		tip_modal.modal();
					        	}
			        		},
			        		error: function() {},
			        		complete : function() {
			        			btn_sure.attr('disable', false);
			        		}
			        	});
		        	});
		        },
		        'click .edit': function (e, value, row, index) {
		        	var editdata = row;
		        	var modalObj = box.loadUpdateModal('subContent', "修改成员"),
	    				modalId = modalObj.modalId, modalBodyId = modalObj.modalBodyId, btnSure = modalObj.btnSure;
		        	var updateUrl = "system/getPage.service?path=system/userUpdate",
	        		 	_target = modalBodyId, _selector = "#person_update";
	        	
		        	orange.loadPage({url: updateUrl, target: _target, selector: _selector, success: function(response) {
		        		var modal = $('#' + modalId), 
	        				btn_sure = $('#' + btnSure);
		    			$('#'+formId2).form('load', editdata);
		    			$('#person_update_form').data('row',row);
		    			modal.modal({backdrop: "static"});
		    			btn_sure.unbind('click').bind('click', function() {
		    				/*整体页面校验*/
							$('#person_update_form').data('bootstrapValidator').validate();
							var submitData = {}, flag = $('#person_update_form').data('bootstrapValidator').isValid();
							if(flag) {
								btn_sure.attr('disable', true);
			    				submitData = $('#'+formId2).form('getFormData', {id:formId2});
			    				submitData['rids'] = $('#update_rolename').val().toString();
			    				$.ajax({
			    					url: 'user/updateUser.service',
			    					type: 'post',
			    					data: submitData,
			    					success: function(data) {
			    						var modalObj = box.tipModal('subContent'),
			    			        		modalId = modalObj.modalId, modalBodyId = modalObj.modalBodyId;
			    			        	var tip_modal = $('#' + modalId);
			    						if(data && data.success) {
			    							getUsers($('#person_add').data('oid'));
				    	    	            modal.modal('hide');
				    	    	            $('#' + modalBodyId).html('成员修改成功！！');
							        		tip_modal.modal();
			    						} else {
			    							 modal.modal('hide');
			    							if(data.errorCode == "2001" || data.errorCode == "1002"){
			    				        		$('#' + modalBodyId).html('成员修改失败。。。。');
			    				        	}else{
			    				        		$('#' + modalBodyId).html('成员修改失败，网络异常。。。。');
			    				        	}
		    				        		tip_modal.modal();
			    						}
			    					},
			    					complete: function() {
			    						btn_sure.attr("disabled", false);
			    					},
			    					error: function() {}
			    				});
							}
		    			});
		        	}});
		        },
		        'click .resetpass': function(e, value, row, index) {
	    				$.ajax({
	    					url: 'user/resetUserPassword.service',
	    					type: 'post',
	    					data: {username: row.username},
	    					success: function(data) {
	    						var modalObj = box.tipModal('subContent'),
	    			        		modalId = modalObj.modalId, modalBodyId = modalObj.modalBodyId;
	    			        	var tip_modal = $('#' + modalId);
	    						if(data && data.success) {
	    							$('#' + modalBodyId).html('重置密码成功！！');
					        		tip_modal.modal();
	    						} else if(data && data.success == false) {
	    							$('#' + modalBodyId).html('重置密码失败！！');
					        		tip_modal.modal();
	    						} else {
	    							alert("error");
	    						}
	    					}
		        	});
		        },
		        'click .group': function (e, value, row, index) {
		        	var modal = $('#read_only_modal'), uid = row.id;
		        	modal.modal();
	        		$.ajax({
						url: 'role/retrieveRolesUserRefByUid.service',
						type: 'post',
						data: {
							uid: uid
						},
						success: function(data) {
							if(data && data.success) {
								var _data = data.data, dataLen = _data.length, sRid = "",
									oLis = $('#read_only_user_role .group-list').find('li'), i=0;
								oLis.each(function(li) {
									$(this).removeClass("selected");
								});
								for(; i<dataLen; i++) {
									sRid = _data[i].rid;
									oLis.each(function(li) {
										if($(this).attr('li-index') &&  $(this).attr('li-index') == sRid) {
											$(this).addClass("selected");
										}
									});
								}
							} else if(data && data.success == false) {
								alert(data.errorMsg);
							} else {
								alert("error");
							}
						}
					});
		        }
		    };
		    
		    $addBtn.click(function () {
		    	//弹出模态框
		    	var modalObj = box.loadCreateModal('subContent', "创建成员"),
	    			modalId = modalObj.modalId, modalBodyId = modalObj.modalBodyId, btnSure = modalObj.btnSure,
		    		createUrl = "system/getPage.service?path=system/userCreate",
		    		_target = modalBodyId, _selector = "#person_create";
       	
	        	orange.loadPage({url: createUrl, target: _target, selector: _selector, success: function(response) {
	        		var modal = $('#' + modalId), 
        				btn_sure = $('#' + btnSure);
	        		modal.modal({backdrop: "static"});
					
					btn_sure.unbind('click').bind('click', function(btn) {
						/*整体页面校验*/
						$('#person_create_form').data('bootstrapValidator').validate();
						var jsonData = {}, flag = $('#person_create_form').data('bootstrapValidator').isValid();
						if(flag) {
							btn_sure.attr("disabled", true);
							jsonData = $('#'+formId).form('getFormData', {id:formId});
							jsonData['oid'] = $('#person_add').data('oid');
							jsonData['rids'] = $('#create_rolename').val().toString();
							$.ajax({
		    					url: 'user/createUser.service',
		    					type: 'post',
		    					data: jsonData,
		    					success : function(data) {
		    						var modalObj = box.tipModal('subContent'),
		    			        		modalId = modalObj.modalId, modalBodyId = modalObj.modalBodyId;
		    			        	var tip_modal = $('#' + modalId);
		    						if(data && data.success) {
		    							$table.bootstrapTable('prepend', data.data);
		        	    	            modal.modal('hide');
		    						} else {
		    							modal.modal('hide');
		    							if(data.errorCode == "1002" || data.errorCode == "3001"){
		    				        		$('#' + modalBodyId).html('成员创建失败。。。。');
		    				        	}else if(data.erroeCode == "2003"){
		    				        		$('#' + modalBodyId).html('成员创建失败，该条数据已存在。。。。');
		    				        	}else{
		    				        		$('#' + modalBodyId).html('成员创建失败，网络异常。。。。');
		    				        	}
		    				        	tip_modal.modal();
		    						}
		    					},
		    					error: function() {},
		    					complete: function() {
		    						btn_sure.attr("disabled", false);
		    					}
		    				});
						}
					});
		    	}});
		    });
			return {initTable: initTable};
		};
		function getUsers(oid) {
			$.ajax({
				url:'user/retrieveUsers.service',
				type:"post",
				data: {oid: oid},
				success: function(data) {
					var rowData = data.data;
					$('#pseron_retrieve').bootstrapTable('load', rowData);
				}
			});
		}
		
		var obj = {
				columns:[
					{width: '16%',field: 'username',title: '用户名',align: 'center'},
	      			{width: '16%',field: 'name',title: '姓名',align: 'center'},
	      			{width: '8%',field: 'gender',title: '性别',align: 'center'},
	      			{width: '16%',field: 'telephone',title: '联系电话',align: 'center'},
	      			{width: '26%',field: 'email',title: '用户邮箱',align: 'center'}],
				mainId : 'subContent',
				tableId : 'pseron_retrieve',	//jquery包装table对象，使其能够调用扩展后jquery的方法
				addBtnId : 'person_add',
				formId : 'person_create_form',
				formId2 : 'person_update_form',
			};
		var initTable = tableFn(obj).initTable;
		//次级导航表
		var opts = {
				type: 'TITLE',
				position: 'SUBTOPLARGE',
				selected: '',
				data: [],
				field: {},
				onSelect: function(item) {
					var _oid = item.id;
					$('#person_add').data('oid', _oid);
					initTable();
					getUsers(_oid);
				},
				onLoaded: function() {
					console.log('navSubTop组件创建完成');
				}
			};
		
		$.ajax({
			url: 'organization/retrieveOrganizations.service',
			type: 'get',
			success: function(data) {
				var _data = data.data;
				var _field = {title: 'name'};
				var subTopIndex = $('#content').data('per_index');
				opts.data = _data;
				opts.field = _field;
				opts.selected = subTopIndex || '0';
				per_nav = navigation.create('#user_navTop', opts);
				//样式调整
				$('#user_navTop').removeClass("column");
				$('#user_navTop').find('ul').removeClass("column");
				$('#user_navTop').find('a').removeClass("card");
			}
		});
		
		if($('#read_only_modal').length < 1) {
    		$('#subContent').append(readOnlyModal);
    	}
    	orange.loadPage({url: "system/getPage.service?path=system/userRoleRef", 
    		target: "read_only_body", 
			selector: "#read_only_user_role", 
			success: function(response) {
	    		if(!response) {
	    			throw new Error("加载失败");
	    		}
	    	}
    	});
		
	});
})();
